import logging
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import Dict, Any
from datetime import timedelta

from .models import UserCreate, UserLogin, UserResponse, UserProfile, Token
from .services import UserService
from core.database import get_db
from core.auth import AuthService, get_current_active_user

# 配置日志
logger = logging.getLogger(__name__)

# 创建路由器
router = APIRouter(prefix="/api/v1/auth", tags=["认证"])

class AuthViews:
    """认证视图类，提供统一的错误处理和响应格式"""
    
    @staticmethod
    def handle_service_error(error: Exception, operation: str) -> HTTPException:
        """统一服务错误处理"""
        if isinstance(error, ValueError):
            logger.warning(f"{operation}失败: {str(error)}")
            return HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=str(error)
            )
        else:
            logger.error(f"{operation}异常: {str(error)}")
            return HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"{operation}失败，请稍后重试"
            )
    
    @staticmethod
    def create_success_response(message: str, data: Any = None) -> Dict[str, Any]:
        """创建统一成功响应格式"""
        response = {
            "success": True,
            "message": message
        }
        if data is not None:
            response["data"] = data
        return response

@router.post("/register", response_model=Dict[str, Any], status_code=status.HTTP_201_CREATED)
def register_user(
    user_data: UserCreate,
    db: Session = Depends(get_db)
) -> Dict[str, Any]:
    """用户注册接口"""
    try:
        # 创建用户
        user = UserService.create_user(db, user_data)
        
        # 返回用户信息（不包含密码）
        user_response = UserResponse.model_validate(user)
        
        return AuthViews.create_success_response(
            "用户注册成功",
            {"user": user_response.model_dump()}
        )
        
    except Exception as e:
        raise AuthViews.handle_service_error(e, "用户注册")

@router.post("/login", response_model=Token)
def login_for_access_token(
    login_data: UserLogin,
    db: Session = Depends(get_db)
) -> Token:
    """用户登录获取JWT token"""
    try:
        # 1. 验证用户凭据
        user = UserService.authenticate_user(db, login_data)
        if not user:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="邮箱或密码错误",
                headers={"WWW-Authenticate": "Bearer"},
            )
        
        # 2. 生成JWT token
        access_token_expires = timedelta(minutes=30)
        access_token = AuthService.create_access_token(
            data={"sub": str(user.id)}
        )
        
        # 3. 创建用户资料信息
        user_profile = UserProfile(
            id=user.id,
            username=user.username,
            email=user.email,
            avatar_url=user.avatar_url,
            is_active=user.is_active,
            created_at=user.created_at,
            updated_at=user.updated_at
        )
        
        # 4. 返回token和用户信息
        return Token(
            access_token=access_token,
            token_type="bearer",
            user=user_profile
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise AuthViews.handle_service_error(e, "用户登录")

@router.post("/refresh", response_model=Token)
def refresh_token(current_user = Depends(get_current_active_user)) -> Token:
    """刷新访问token"""
    try:
        # 生成新的access token
        access_token = AuthService.create_access_token(
            data={"sub": str(current_user.id)}
        )
        
        # 创建用户资料信息
        user_profile = UserProfile(
            id=current_user.id,
            username=current_user.username,
            email=current_user.email,
            avatar_url=current_user.avatar_url,
            is_active=current_user.is_active,
            created_at=current_user.created_at,
            updated_at=current_user.updated_at
        )
        
        return Token(
            access_token=access_token,
            token_type="bearer",
            user=user_profile
        )
        
    except Exception as e:
        raise AuthViews.handle_service_error(e, "刷新token")

@router.get("/me", response_model=Dict[str, Any])
def get_current_user_info(
    current_user: User = Depends(get_current_active_user)
) -> Dict[str, Any]:
    """获取当前用户信息接口（需要认证）"""
    try:
        # 创建用户资料信息
        user_profile = UserProfile(
            id=current_user.id,
            username=current_user.username,
            email=current_user.email,
            avatar_url=current_user.avatar_url,
            is_active=current_user.is_active,
            created_at=current_user.created_at,
            updated_at=current_user.updated_at
        )
        
        return AuthViews.create_success_response(
            "获取用户信息成功",
            {"user": user_profile.model_dump()}
        )
        
    except Exception as e:
        raise AuthViews.handle_service_error(e, "获取用户信息")

@router.post("/logout", response_model=Dict[str, Any])
def logout_user() -> Dict[str, Any]:
    """用户登出接口"""
    try:
        # 在JWT实现中，这里可以将token加入黑名单
        # 或者简单地让前端删除token
        
        return AuthViews.create_success_response("登出成功")
        
    except Exception as e:
        raise AuthViews.handle_service_error(e, "用户登出")